//
//  YYSeraviceGoodsDetailVC.m
//  drivingSchool
//
//  Created by 子yu 刘 on 2018/11/18.
//  Copyright © 2018年 子yu 刘. All rights reserved.
//

#import "YYSeraviceGoodsDetailVC.h"
#import "YYPayVC.h"

@interface YYSeraviceGoodsDetailVC ()<UIWebViewDelegate>

@property (nonatomic ,strong)NSDictionary * dataDic;

@end

@implementation YYSeraviceGoodsDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.webView.scrollView.scrollEnabled = NO;
    self.webView.delegate = self;
    [self getData];
    self.shawView.layer.shadowOffset = CGSizeMake(1, 1);
    self.shawView.layer.shadowOpacity = 0.8;
    self.shawView.layer.shadowColor = [UIColor colorWithWhite:0.7 alpha:1].CGColor;
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    NSString *js = @"function imgAutoFit() { \
    var imgs = document.getElementsByTagName('img'); \
    for (var i = 0; i < imgs.length; ++i) {\
    var img = imgs[i];   \
    img.style.maxWidth = %f;   \
    } \
    }";
    js = [NSString stringWithFormat:js, [UIScreen mainScreen].bounds.size.width - 20];
    
    [webView stringByEvaluatingJavaScriptFromString:js];
    [webView stringByEvaluatingJavaScriptFromString:@"imgAutoFit()"];
    self.webViewHeight.constant = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight"] floatValue];
}


- (void)getData{
    [RequestOperationManager serviceGoodsDetail_id:self.gid success:^(id result) {
        if (DEF_REQ_SUCCESS) {
            self.dataDic = [result[@"data"] copy];
            [self reoadData];
        }
        
    } failture:^(NSError *error) {
        
    }];
}

- (void)reoadData{
    self.lbGoodName.text = self.dataDic[@"name"];
    [self.bigImg sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",DEF_INTERFACE_WEBVIEWSERVICE,self.dataDic[@"seller_img"]]]];
    [self.bigImg sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",DEF_INTERFACE_WEBVIEWSERVICE,self.dataDic[@"seller_img"]]] placeholderImage:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            self.bigImg.image = [CFUtility blurryImage:image withBlurLevel:18.0];
    }];
    self.lbContent.text = self.dataDic[@"content"];
    [self.webView loadHTMLString:self.dataDic[@"product_img"] baseURL:nil];
    if ([self.dataDic[@"is_exchange"] isEqualToString:@"3"]) {
         self.lbPrice.text = [NSString stringWithFormat:@"￥%@",self.dataDic[@"price"]];
    } else if ([self.dataDic[@"is_exchange"] isEqualToString:@"1"]){
         self.lbPrice.text = [NSString stringWithFormat:@"%@积分+￥%@",self.dataDic[@"pay_integral"],self.dataDic[@"price"]];
    }else{
         self.lbPrice.text = [NSString stringWithFormat:@"%@积分",self.dataDic[@"pay_integral"]];
    }
   
}
- (IBAction)exchange:(id)sender {
    if ([self.dataDic[@"is_exchange"] isEqualToString:@"3"]||[self.dataDic[@"is_exchange"] isEqualToString:@"1"]) {
        [self pay];
    }else{
        [ASAlertViewController getAlertControllerWithTitle:nil message:[NSString stringWithFormat:@"扣除%@积分",self.dataDic[@"pay_integral"]] sureTitle:@"确定" cancelTitle:@"取消" viewController:self sureAction:^(UIAlertAction *action) {
      
                [self exchange];
            
        } cancelAction:nil];
    }
}

- (void)pay{
    YYPayVC * pay = (YYPayVC *)[CFUtility getVC:@"YYPayVC" Storyboard:HOME];
    pay.isHidden = YES;
    pay.money = self.dataDic[@"price"] ;
    pay.payBlock = ^(NSString *type) {
        [RequestOperationManager serviceProductbuy_product:self.dataDic[@"name"] product_id:self.gid integral:self.dataDic[@"pay_integral"] money:self.dataDic[@"price"] seller_id:self.dataDic[@"seller_id"] is_exchange:self.dataDic[@"is_exchange"] pay:type success:^(id result) {
            if (DEF_REQ_SUCCESS) {
                if ([type isEqualToString:@"0"]) {
                    [self aliPayWithSign:result[@"data"]];
                }else{
                    [self wechatPayWithResponse:result[@"data"]];
                }
            }
        } failture:^(NSError *error) {
            
        }];
    };
    [self.navigationController pushViewController:pay animated:YES];
}

- (void)exchange{
    [RequestOperationManager serviceExchange_product:self.dataDic[@"name"] product_id:self.gid integral:self.dataDic[@"pay_integral"] is_exchange:self.dataDic[@"is_exchange"] seller_id:self.dataDic[@"seller_id"] success:^(id result) {
        if (DEF_REQ_SUCCESS) {
            [AlertUtil alertMessage:@"兑换成功"];
        }
        
    } failture:^(NSError *error) {
        
    }];
}
- (void)wechatPayWithResponse:(NSDictionary *)response {
    PayReq* req  = [[PayReq alloc] init];
    req.partnerId = response[@"partnerid"];
    req.prepayId= response[@"prepayid"];
    req.package = response[@"package"];
    req.nonceStr= response[@"noncestr"];
    req.timeStamp= [response[@"timestamp"] intValue];
    req.sign=response[@"sign"];
    [FLPAYMANAGER fl_payWithOrderMessage:req callBack:^(FLErrCode errCode, NSString *errStr, NSDictionary *resultDic) {
        
        if (errCode == FLErrCodeSuccess) {
            YYHintVC * hint = (YYHintVC *)[CFUtility getVC:@"YYHintVC" Storyboard:INSURANCE];
            NSDictionary * data = @{@"title":@"支付成功",
                                    @"image":@"sign_success",
                                    @"content":@"客服稍后会联系您，请保持电话畅通谢谢"
                                    };
            hint.viewDict = data;
            [self.navigationController pushViewController:hint animated:YES];
        }else{
            [AlertUtil alertMessage:errStr];
        }
    }];
}

- (void)aliPayWithSign:(NSString * )sign{
    /**
     *  @author gitKong
     *
     *  来自支付宝文档数据
     */
    
    [FLPAYMANAGER fl_payWithOrderMessage:sign callBack:^(FLErrCode errCode, NSString *errStr, NSDictionary *resultDic) {
        if (resultDic&&[resultDic[@"resultStatus"] isEqualToString:@"9000"]) {
            YYHintVC * hint = (YYHintVC *)[CFUtility getVC:@"YYHintVC" Storyboard:INSURANCE];
            NSDictionary * data = @{@"title":@"支付成功",
                                    @"image":@"sign_success",
                                    @"content":@"客服稍后会联系您，请保持电话畅通谢谢"
                                    };
            hint.viewDict = data;
            [self.navigationController pushViewController:hint animated:YES];
        }else{
            [AlertUtil alertMessage:errStr];
            
        }
        
    }];
    
    
}


- (NSString *)jumpToBizPay {
    //============================================================
    /**
     *  @author Clarence
     *
     *  来自微信文档数据
     */
    //============================================================
    NSString *urlString   = @"http://wxpay.weixin.qq.com/pub_v2/app/app_pay.php?plat=ios";
    //解析服务端返回json数据
    NSError *error;
    //加载一个NSURL对象
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    //将请求的url数据放到NSData对象中
    NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    if ( response != nil) {
        NSMutableDictionary *dict = NULL;
        //IOS5自带解析类NSJSONSerialization从response中解析出数据放到字典中
        dict = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
        NSLog(@"url:%@",urlString);
        if(dict != nil){
            NSMutableString *retcode = [dict objectForKey:@"retcode"];
            if (retcode.intValue == 0){
                NSMutableString *stamp  = [dict objectForKey:@"timestamp"];
                //调起微信支付
                PayReq* req             = [[PayReq alloc] init];
                req.partnerId           = [dict objectForKey:@"partnerid"];
                req.prepayId            = [dict objectForKey:@"prepayid"];
                req.nonceStr            = [dict objectForKey:@"noncestr"];
                req.timeStamp           = stamp.intValue;
                req.package             = [dict objectForKey:@"package"];
                req.sign                = [dict objectForKey:@"sign"];
                
                [FLPAYMANAGER fl_payWithOrderMessage:req callBack:^(FLErrCode errCode, NSString *errStr, NSDictionary *resultDic) {
                    NSLog(@"errCode = %zd,errStr = %@",errCode,errStr);
                }];
                //日志输出
                NSLog(@"appid=%@\npartid=%@\nprepayid=%@\nnoncestr=%@\ntimestamp=%ld\npackage=%@\nsign=%@",[dict objectForKey:@"appid"],req.partnerId,req.prepayId,req.nonceStr,(long)req.timeStamp,req.package,req.sign );
                return @"";
            }else{
                return [dict objectForKey:@"retmsg"];
            }
        }else{
            return @"服务器返回错误，未获取到json对象";
        }
    }else{
        return @"服务器返回错误";
    }
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
